package com.financing.wap.common;

import java.io.IOException;
import java.io.OutputStream;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;


public class QRCodeUtil {
	 /** 
     * 生成二维码(QRCode)图片 
     * @param content 存储内容 
     * @param output 输出流 
	 * @throws IOException 
	 * @throws WriterException 
     */  
    public static void encoderQRCode(String content, OutputStream output) throws Exception{  
        int width = 240;   
        int height = 240;   
        String format = "png";   
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height);   
        MatrixToImageWriter.writeToStream(bitMatrix, format, output);
    } 
    
    /** 
     * 生成二维码(QRCode)图片 
     * @param content 存储内容 
     * @param output 输出流 
	 * @throws IOException 
	 * @throws WriterException 
     */  
    public static void encoderQRCode(String content, OutputStream output,int width,int height) throws Exception{  
        String format = "png";   
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height);   
        MatrixToImageWriter.writeToStream(bitMatrix, format, output);
    } 
    
    /** 
     * 生成二维码(QRCode)图片  去除边距
     * @param content 存储内容 
     * @param output 输出流 
	 * @throws IOException 
	 * @throws WriterException 
     */  
    public static void encoderQRCodeNoBorder(String content, OutputStream output,int width,int height) throws Exception{  
        String format = "png";   
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height);   
        int[] rec = bitMatrix.getEnclosingRectangle();  
        int resWidth = rec[2] + 1;  
        int resHeight = rec[3] + 1;  
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);  
        resMatrix.clear();  
        for (int i = 0; i < resWidth; i++) {  
            for (int j = 0; j < resHeight; j++) {  
                if (bitMatrix.get(i + rec[0], j + rec[1])) { 
                     resMatrix.set(i, j); 
                } 
            }  
        }  
        MatrixToImageWriter.writeToStream(resMatrix, format, output);
    } 
}
